package com.ocom.webapi;


import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.util.Base64;

public class PfxDecode {

    public static void main(String[] args) {
        try {
            String rootPath = PfxDecode.class.getResource("/").getPath().split("target")[0];
            System.out.println("项目根路径：" + rootPath);

            // PFX文件路径
            String pfxFilePath = rootPath +"src/test/java/com/ocom/webapi/privateKey.pfx";
            // PFX文件密码
            char[] pfxPassword = "123456".toCharArray();

            // 初始化KeyStore
            KeyStore keystore = KeyStore.getInstance("PKCS12");
            keystore.load(new FileInputStream(pfxFilePath), pfxPassword);

            // 获取别名
//            String alias = "your_alias"; // 替换为PFX文件中的别名
            String alias = keystore.aliases().nextElement();
            System.out.println("alias：" + alias);


            // 获取私钥
            PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, pfxPassword);
            // 获取证书
            Certificate cert = keystore.getCertificate(alias);
            // 获取公钥
            PublicKey publicKey = cert.getPublicKey();

            // 输出密钥信息
            System.out.println("Private Key: " + convertPrivateKeyToString(privateKey));
            System.out.println("Public Key: " + convertPublicKeyToString(publicKey));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 将私钥转换为字符串
    private static String convertPrivateKeyToString(PrivateKey privateKey) {
        byte[] privateKeyBytes = privateKey.getEncoded();
        return Base64.getEncoder().encodeToString(privateKeyBytes);
    }
    private static String convertPublicKeyToString(PublicKey privateKey) {
        byte[] privateKeyBytes = privateKey.getEncoded();
        return Base64.getEncoder().encodeToString(privateKeyBytes);
    }
}